<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>浙江工商大学食堂点单管理系统 - 客户界面</title>
    <style>
        /* 重置盒模型 */
        *, *::before, *::after {
            box-sizing: border-box;
        }

        /* 顶部导航栏 */ 
        .header {
            width: 100%;
            background-color: #fff;
            padding: 10px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            position: fixed;
            top: 0;
            left: 0;
            z-index: 1000;
        }
        .header img {
            height: 40px;
        }
        .header .search {
            display: flex;
            align-items: center;
        }
        .header .search input {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            outline: none;
        }
        .header .search button {
            background-color: #007bff;
            border: none;
            color: white;
            padding: 8px;
            margin-left: 8px;
            border-radius: 4px;
            cursor: pointer;
        }
        .header .search button img {
            height: 16px;
        }

        /* 产品列表 */
        .products {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 20px;
            margin-top: 60px; /* 调整为header的高度 */
            padding: 20px;
        }
        .product {
            background-color: #fff;
            width: calc(25% - 20px); /* 四列布局，减去gap */
            min-width: 200px; /* 最小宽度 */
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            text-align: center;
            margin-bottom: 70px; 
        }
        .product img {
            width: 100%;
            height: auto;
            border-radius: 8px;
        }
        .product h3 {
            font-size: 18px;
            margin: 10px 0;
        }
        .product button {
            background-color: #007bff;
            border: none;
            color: white;
            padding: 10px;
            border-radius: 4px;
            cursor: pointer;
            width: 100%;
        }
        .product p {
            font-size: 14px;
            color: #ff6347; /* 使用红色或者其他醒目的颜色 */
            font-weight: bold;
        }

        /* 按钮容器，确保按钮并排显示并有较大间距 */
        .button-container {
            display: flex;
            justify-content: space-between;
            gap: 20px; /* 设置按钮之间的间距为20px，可以根据需要调整 */
            margin-top: 10px; /* 为按钮添加顶部间距 */
        }

        /* 购物车按钮 */
        .cart-button {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background-color: #007bff;
            border: none;
            color: white;
            padding: 10px 20px;
            border-radius: 50%;
            cursor: pointer;
            font-size: 24px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }

        /* 商品页面按钮样式 */
        .product .button-container button {
            background-color: #007bff;
            border: none;
            color: white;
            padding: 10px;
            border-radius: 4px;
            cursor: pointer;
            width: 48%; /* 确保按钮宽度适中，避免撑满父容器 */
        }

        .product .button-container button:hover {
            background-color: #0056b3;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.5);
        }
        .modal-content {
            background-color: #fff;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
            max-width: 500px;
            border-radius: 8px;
        }
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }
        .close:hover,
        .close:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }

        /* 媒体查询 */
        @media (max-width: 768px) {
            .product {
                width: calc(50% - 20px); /* 两列布局 */
            }
        }

        @media (max-width: 480px) {
            .product {
                width: 100%; /* 单列布局 */
            }
        }
        .footer-buttons {
            width: 100%; 
            background-color: #ffffff;
            color: #fff; 
            position: fixed; 
            bottom: 0; 
            left: 0; 
            z-index: 1000; 
            padding: 10px 0; 
            display: flex; 
            justify-content: space-between;
            box-shadow: 0 -4px 8px rgba(0, 0, 0, 0.1);
            padding-left: 10px; 
            padding-right: 10px; 
        }
        .footer-buttons button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            text-align: center;
        }
        .footer-buttons button:hover {
            background-color: #0056b3;
        }

    </style>
</head>
<body>
    <div class="container">
        <!-- 顶部 -->
        <div class="header">
            <img src="./images/cafeteria-logo.png" alt="Logo">
            <div class="search">
                <input type="text" id="searchInput" placeholder="搜索商品">
                <button id="searchButton">
                    <img src="./images/icon_search.png" class="icon">
                </button>
            </div>
            <div class="user">
                <span id="userPhone">你好，<span id="userPhoneNumber"></span></span>
            </div>
        </div>

        <!-- 产品列表 -->
        <div class="products" id="products">
            <!-- 产品加载 -->
        </div>

        <div class="footer-buttons">
            <a href="consumer-dashboard.html">
                <button>菜单</button>
            </a>
            <a href="cart.html">
                <button>购物车</button>
            </a>
            <a href="rank.html">
                <button>排行榜</button>
            </a>
            <a href="my.html">
                <button>我的</button>
            </a>
        </div>
    </div>

    <!-- 模态框 -->
    <div id="orderModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeOrderModal()">&times;</span>
            <h3 id="modalProductName"></h3>
            <p id="modalProductDescription"></p>
            <p>价格: ¥<span id="modalProductPrice"></span></p>
            <label for="quantity">数量:</label>
            <input type="number" id="quantity" name="quantity" min="1" value="1">
            <button onclick="addToCart()">加入购物车</button>
        </div>
    </div>

    <!-- 评论模态框 -->
    <div id="comments-modal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal()">&times;</span>
            <h3 id="modalProductName"></h3>
            <p id="modalProductDescription"></p>

            
            <!-- 显示平均评分 -->
            <p id="modalProductRating"></p>

            <!-- 商品评论内容 -->
            <div id="modalCommentsContainer"></div>


        </div>
    </div>








    <script>
        // 加载用户信息
        function loadUserInfo() {
            fetch('/api/user_info')
                .then(response => response.json())
                .then(data => {
                    userPhone = data.phone_number;
                    document.getElementById('userPhoneNumber').innerText = userPhone || '未知';
                }).catch(error => {
                    console.error('Failed to fetch user info:', error);
                    document.getElementById('userPhoneNumber').innerText = '未知';
                });
        }
        document.addEventListener('DOMContentLoaded', function() {
            loadUserInfo();
        });

        // 加载产品数据
        function loadProducts(query = '') {
            fetch('/api/products')
                .then(response => response.json())
                .then(data => {
                    const productsContainer = document.getElementById('products');
                    productsContainer.innerHTML = ''; // 清空现有的产品列表

                    data.products.forEach(product => {
                        if (query && !product.name.toLowerCase().includes(query.toLowerCase())) {
                            return;
                        }

                        // 获取当前商品的窗口ID
                        const windowId = product.window_id;

                        // 获取该窗口的排队人数
                        fetch(`/api/window_queue_count/${windowId}`)
                            .then(response => response.json())
                            .then(queueData => {
                                const queueCount = queueData.queue_count;

                                // 创建商品展示元素
                                const productDiv = document.createElement('div');
                                productDiv.className = 'product';
                                productDiv.innerHTML = `
                                    <img src="/images/products/${product.picture_path}" alt="${product.name}" />
                                    <h3>${product.name}</h3>
                                    <p>价格: ¥${product.price}</p>
                                    <p>排队人数: ${queueCount} 人</p> <!-- 显示排队人数 -->

                                    <!-- 放置两个按钮的容器 -->
                                    <div class="button-container">
                                        <button onclick='openOrderModal(${JSON.stringify(product)})'>加入购物车</button>
                                        <button onclick='viewComments(${product.id})'>查看评论</button>
                                    </div>

                                    <!-- 商品评论展示区域 -->
                                    <div id="product-${product.id}-comments"></div>
                                `;
                                productsContainer.appendChild(productDiv);
                            })
                            .catch(error => {
                                console.error('Failed to load window queue count:', error);
                            });
                    });
                })
                .catch(error => {
                    console.error('Failed to load products:', error);
                });
        }


        // 打开弹窗
        function openOrderModal(product) {
            selectedProduct = product;
            document.getElementById('modalProductName').innerText = product.name;
            document.getElementById('modalProductDescription').innerText = product.description;
            document.getElementById('modalProductPrice').innerText = product.price;
            document.getElementById('orderModal').style.display = 'block';
        }

        // 关闭弹窗
        function closeOrderModal() {
            document.getElementById('orderModal').style.display = 'none';
            selectedProduct = null;
        }

        // 加入购物车
        function addToCart() {
            const quantity = document.getElementById('quantity').value;
            if (!selectedProduct) return;

            fetch('/api/cart', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    product_id: selectedProduct.id,
                    quantity: quantity
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('商品已加入购物车');
                    closeOrderModal();
                } else {
                    alert('加入购物车失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('加入购物车失败');
            });
        }

        // 搜索功能
        document.getElementById('searchButton').addEventListener('click', function() {
            const query = document.getElementById('searchInput').value;
            loadProducts(query);
        });

// 查看评论
// 查看评论
        function viewComments(productId) {
            fetch(`/api/products/${productId}/comments`)
                .then(response => response.json())
                .then(data => {
                    const commentsContainer = document.getElementById('modalCommentsContainer');
                    const modalProductName = document.getElementById('modalProductName');
                    const modalProductDescription = document.getElementById('modalProductDescription');
                    const modalProductPrice = document.getElementById('modalProductPrice');
                    const modalProductRating = document.getElementById('modalProductRating');

                    // 获取商品的平均评分
                    let totalRating = 0;
                    let commentCount = data.comments.length;
                    
                    // 计算平均评分
                    if (commentCount > 0) {
                        data.comments.forEach(comment => {
                            totalRating += comment.rating;
                        });
                        const averageRating = (totalRating / commentCount).toFixed(1); // 保留一位小数
                        // 显示平均评分
                        modalProductRating.innerText = `平均评分: ${averageRating} 星`;
                    } else {
                        modalProductRating.innerText = '暂无评论';
                    }

                    // 显示评论内容
                    let commentsHtml = "<h4>商品评论：</h4>";
                    data.comments.forEach(comment => {
                        commentsHtml += `
                            <div class="comment">
                                <p><strong>评论内容:</strong> ${comment.comment}</p>
                            </div>
                        `;
                    });

                    // 将评论显示在模态框中
                    modalProductName.innerText = data.product.name;
                    modalProductDescription.innerText = data.product.description;
                    modalProductPrice.innerText = `价格: ¥${data.product.price}`;

                    commentsContainer.innerHTML = commentsHtml;

                    // 显示模态框
                    document.getElementById("comments-modal").style.display = "block";
                })
                .catch(error => {
                    console.error('Failed to fetch comments:', error);
                    alert('加载评论失败，请稍后重试。');
                });
        }

        // 关闭评论模态框
        function closeModal() {
            document.getElementById("comments-modal").style.display = "none";
        }



        document.addEventListener('DOMContentLoaded', function() {
            loadProducts();
        });



    </script>
    
</body>
</html>